/**
 * 系统管理 用户管理
 */
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="query" class="user-search">
      <el-form-item label="搜索：">
        <el-select size="small" v-model="query.IsDel" placeholder="请选择">
           <el-option label="全部" value=""></el-option>
          <el-option label="正常" value="0"></el-option>
          <el-option label="已禁用" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="">
        <el-input
          size="small"
          v-model="query.UserName"
          placeholder="输入用户名"
        ></el-input>
      </el-form-item>
      <el-form-item label="">
        <el-input
          size="small"
          v-model="query.Name"
          placeholder="输入姓名"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-search"
          @click="search"
          >搜索</el-button
        >
        <el-button
          v-permission="['add', $route]"
          size="small"
          type="primary"
          icon="el-icon-plus"
          @click="handleEdit()"
          >添加</el-button
        >
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table
      size="small"
      @selection-change="selectChange"
      :data="userData"
      highlight-current-row
      v-loading="loading"
      border
      element-loading-text="拼命加载中"
      style="width: 100%"
    >
      <el-table-column align="center" type="selection" width="50">
      </el-table-column>

      <el-table-column
        align="center"
        sortable
        prop="UserName"
        label="用户名"
        width="120"
      >
      </el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="Name"
        label="姓名"
        width="120"
      >
      </el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="NickName"
        label="昵称"
        width="120"
      >
      </el-table-column>
      <el-table-column align="center" sortable label="角色名称" width="120">
        <template slot-scope="scope">
          {{ !!scope.row.role ? scope.row.role.Name : "" }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="CreateTime"
        label="添加时间"
        min-width="120"
      >
      </el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="IsDel"
        label="状态"
        min-width="50"
      >
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.IsDel == '0'">正常</el-tag>
          <el-tag type="danger" v-else>禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="300">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.$index, scope.row)"
            v-permission="['edit', $route]"
            >编辑</el-button
          >
          <el-button
            v-permission="['state', $route]"
            size="mini"
            :type="scope.row.IsDel == '0' ? 'danger' : 'success'"
            @click="deleteUser(scope.$index, scope.row)"
            >{{ scope.row.IsDel == "0" ? "禁用" : "正常" }}</el-button
          >
          <el-button
            v-permission="['repas', $route]"
            size="mini"
            type="success"
            @click="resetpwd(scope.$index, scope.row)"
            >重置密码</el-button
          >
          <el-button
            v-permission="['permissions', $route]"
            size="mini"
            type="success"
            @click="dataAccess(scope.$index, scope.row)"
            >功能权限</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination
      v-bind:child-msg="pageparm"
      @callFather="callFather"
    ></Pagination>
    <!-- 编辑界面 -->
    <el-dialog
      :title="title"
      :visible.sync="editFormVisible"
      width="30%"
      @click="closeDialog('edit')"
    >
      <el-form
        label-width="80px"
        ref="editForm"
        :model="editForm"
        :rules="rules"
      >
        <el-form-item label="用户名" prop="UserName">
          <el-input
            size="small"
            v-model="editForm.UserName"
            auto-complete="off"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="Name">
          <el-input
            size="small"
            v-model="editForm.Name"
            auto-complete="off"
            placeholder="请输入姓名"
          ></el-input>
        </el-form-item>

        <el-form-item label="昵称" prop="NickName">
          <el-input
            size="small"
            v-model="editForm.NickName"
            placeholder="请输入昵称"
          ></el-input>
        </el-form-item>

        <el-form-item label="所在单位" prop="value">
          <el-cascader
            style="width: 100%"
            clearable
            v-model="value"
            :options="companydata"
            :props="{ expandTrigger: 'hover' }"
            @change="handleChange"
          ></el-cascader>
        </el-form-item>

        <el-form-item label="所属角色" prop="RoleGuId">
          <el-select
            v-model="editForm.RoleGuId"
            clearable
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in roles"
              :key="item.GuId"
              :label="item.Name"
              :value="item.GuId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="登入密码"
          prop="Password"
          v-if="editForm.GuId == ''"
        >
          <el-input
            size="small"
            v-model="editForm.Password"
            placeholder="请输入登入密码"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog('edit')">取消</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="loading"
          class="title"
          @click="submitForm('editForm')"
          >保存</el-button
        >
      </div>
    </el-dialog>
    <!-- 数据权限 -->
    <el-dialog
      title="数据权限"
      :visible.sync="dataAccessshow"
      width="70%"
      :close-on-click-modal="false"
      @click="closeDialog('perm')"
    >
      <el-table
        ref="tabletree"
        default-expand-all=""
        :data="permissions.UserDept"
        :props="defaultProps"
        row-key="GuId"
        border
        highlight-current-row
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        @selection-change="handleSelectionChange"
        @select="rowSelect"
        @select-all="selectAll"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="Name" label="菜单名称" width="300">
        </el-table-column>
        <el-table-column prop="" label="功能列表">
          <template slot-scope="scope">
            <div style="display: flex">
              <div
                v-for="item in scope.row.Btnlis"
                :key="item.GuId"
                style="margin-left: 10px"
              >
                <el-checkbox v-model="item.ischecked">{{
                  item.Name
                }}</el-checkbox>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog('perm')">取消</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="loading"
          class="title"
          @click="menuPermSave"
          >保存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 导入请求方法
import { req, reqjson } from "@/api/axiosFun";

import Pagination from "../../components/Pagination";
export default {
  data() {
    return {
      CompanyTreev: [],
      companydata: [], //部门选择数据源
      value: [], //部门选择器
      nshow: true, //switch开启
      fshow: false, //switch关闭
      loading: false, //是显示加载
      title: "添加用户",
      editFormVisible: false, //控制编辑页面显示与隐藏
      dataAccessshow: false, //控制数据权限显示与隐藏
      unitAccessshow: false, //控制所属单位隐藏与显示
      // 编辑与添加
      editForm: {
        GuId: "",
        Name: "",
        NickName: "",
        UserName: "",
        Password: "",
        RoleGuId: "",
        CompanyGuId: "",
        DepartmentGuId: "",
      },
      roles: [],
      // 选择数据
      selectdata: [],
      // rules表单验证
      rules: {
        UserName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        Name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
      },

      // 请求数据参数
      query: {
        UserName: "",
        Name: "",
        IsDel: "",
      },
      //用户数据
      userData: [],
      //权限数据类
      permissions: {
        // 数据权限
        UserDept: [],
        //全部数据
        list: [],
        //用户权限数据
        userRoleAuthorization: [],
        //用户权限选中数据
        selecttree: [],
        usergid: "",
      },

      defaultProps: {
        children: "children",
        label: "Name",
      },
      // 选中
      checkmenu: [],
      //参数role
      saveroleId: "",
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 10,
      },
      //查询数据对象
    };
  },
  // 注册组件
  components: {
    Pagination,
  },

  /**
   * 数据发生改变
   */
  watch: {},

  /**
   * 创建完毕
   */
  created() {
    this.getcompanydata();
    this.getrole();
    this.getdata();
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    //加载角色
    getrole() {
      reqjson(
        "post",
        "/SysUserApi/GetRoles?token=" + this.$jsutils.sessionget("token")
      )
        .then((x) => {
          if (x.success) {
            this.roles = x.data;
          }
        })
        .catch((x) => {
          console.log(x);
        });
    },
    //加载所在单位、部门
    getcompanydata() {
      reqjson(
        "post",
        "/SysCompany/GetCompanyTree?token=" + this.$jsutils.sessionget("token")
      )
        .then((x) => {
          if (x.success) {
            this.companydata = x.data;
          }
        })
        .catch((x) => {
          console.log(x);
        });
    },
    // 获取数据方法
    getdata() {
      let data = {
        page: this.pageparm.currentPage,
        limit: this.pageparm.pageSize,
        data: JSON.stringify(this.query),
      };
      this.loading = true;
      reqjson(
        "post",
        "/SysUserApi/GetUserList?token=" + this.$jsutils.sessionget("token"),
        data
      )
        .then((x) => {
          this.loading = false;
          if (x.success) {
            this.pageparm.currentPage = x.data.CurrentPage;
            this.pageparm.pageSize = x.data.ItemsPerPage;
            this.pageparm.total = x.data.TotalItems;
            this.userData = x.data.Items;
          }
        })
        .catch((x) => {
          this.loading = false;
          console.log(x);
        });
    },
    // 分页插件事件
    callFather(parm) {
      this.formInline.page = parm.currentPage;
      this.formInline.limit = parm.pageSize;
      this.getdata();
    },
    //搜索事件
    search() {
      this.getdata();
    },

    //显示编辑界面
    handleEdit(index, row) {
      this.value = [];
      this.editFormVisible = true;
      if (row != undefined && row != "undefined") {
        this.title = "修改用户";
        this.editForm.GuId = row.GuId;
        this.editForm.Name = row.Name;
        this.editForm.NickName = row.NickName;
        this.editForm.UserName = row.UserName;
        this.editForm.RoleGuId = row.RoleGuId;
        this.editForm.CompanyGuId = row.CompanyGuId;
        this.editForm.DepartmentGuId = row.DepartmentGuId;

        this.value.push(row.CompanyGuId);
        this.value.push(row.DepartmentGuId);
      } else {
        this.title = "添加用户";
        this.editForm.GuId = "";
        this.editForm.Name = "";
        this.editForm.NickName = "";
        this.editForm.UserName = "";
        this.editForm.Password = "";
        this.editForm.RoleGuId = "";
      }
    },
    // 编辑、添加提交方法
    submitForm(editData) {
      this.$refs[editData].validate((valid) => {
        if (valid) {
          if (this.title == "添加用户") {
            if (!this.editForm.Password) {
              this.$message.error("登入密码不能为空！");
            }
          }

          if (this.CompanyTreev.length > 0) {
            this.editForm.CompanyGuId = this.CompanyTreev[0];
            this.editForm.DepartmentGuId = this.CompanyTreev[1];
          }

          this.loading = true;
          reqjson(
            "post",
            "/SysUserApi/AddUser?token=" + this.$jsutils.sessionget("token"),
            this.editForm
          )
            .then((x) => {
              this.loading = false;
              if (x.success) {
                this.value = []; //清空选中的值
                this.editFormVisible = false;
                this.$message.success("操作成功!");
                this.getdata();
              }
            })
            .catch((x) => {
              this.loading = false;
              console.log(x);
            });
        } else {
          return false;
        }
      });
    },

    // 选择复选框事件
    selectChange(val) {
      this.selectdata = val;
    },
    // 关闭编辑、增加弹出框
    closeDialog(dialog) {
      if (dialog == "edit") {
        this.editFormVisible = false;
      } else if (dialog == "perm") {
        this.dataAccessshow = false;
      } else if (dialog == "unit") {
        this.unitAccessshow = false;
      }
    },
    // 修改用户状态
    deleteUser(index, row) {
      this.$confirm("确定要修改状态吗?", "信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.loading = true;
          reqjson(
            "post",
            "/SysUserApi/ModifyState?token=" +
              this.$jsutils.sessionget("token") +
              "&gid=" +
              row.GuId
          )
            .then((x) => {
              this.loading = false;
              if (x.success) {
                this.$message.success("操作成功！");
                this.getdata();
              } else {
                this.$message.error(x.data);
              }
            })
            .catch((x) => {
              this.loading = false;
              this.$message.error("操作失败，请稍后再试！");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除！",
          });
        });
    },
    // 重置密码
    resetpwd(index, row) {
      if (!row.GuId) {
        this.$message.error("重置密码失败，参数错误！");
        return false;
      }

      this.$confirm("确定要重置密码吗?重置密码”sys@123456“", "信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.loading = true;
          reqjson(
            "post",
            "/SysUserApi/ResetPwd?token=" +
              this.$jsutils.sessionget("token") +
              "&gid=" +
              row.GuId
          )
            .then((x) => {
              this.loading = false;
              if (x.success) {
                this.$message.success("重置密码成功！");
                this.getdata();
              } else {
                this.$message.error(x.data);
              }
            })
            .catch((x) => {
              this.loading = false;
              this.$message.error("重置密码失败，请稍后再试！");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消重置密码！",
          });
        });
    },

    // 数据权限
    dataAccess(index, row) {
      this.dataAccessshow = true;
      this.permissions.usergid = row.GuId;
      this.loading = true;
      reqjson(
        "post",
        "/SysUserApi/GetUserMenu?token=" +
          this.$jsutils.sessionget("token") +
          "&gid=" +
          row.GuId
      )
        .then((x) => {
          this.loading = false;
          if (x.success) {
            this.permissions.userRoleAuthorization =
              x.data.userRoleAuthorization;

            this.permissions.list = x.data.list;
            this.permissions.UserDept = this.getmenu("0");

            this.$nextTick(() => {
              this.loadtabletree();
            });
          } else {
            this.$message.error(x.data);
          }
        })
        .catch((x) => {
          this.loading = false;
          console.log(x);
        });
    },
    //权限选中数据
    handleSelectionChange(val) {
      this.permissions.selecttree = val;
    },
    //初始化选中列表
    loadtabletree() {
      this.$refs.tabletree.data.map((items) => {
        //使用$ref获取注册的子组件信息，用data获取所有行，并用map函数遍历行
        if (items.children) {
          if (items.isChecked) {
            //若遍历出来的行未选中
            this.$refs.tabletree.toggleRowSelection(items, true); //行变为选中状态
            items.children.map((item) => {
              if (item.isChecked)
                this.$refs.tabletree.toggleRowSelection(item, true);
            });
          }
        } else {
          if (items.isChecked) {
            this.$refs.tabletree.toggleRowSelection(items, true);
          }
        }
      });
    },

    rowSelect(selection, row) {
      if (row.children) {
        //只对有子节点的行响应
        if (!row.isChecked) {
          //由行数据中的元素isChecked判断当前是否被选中
          row.children.map((item) => {
            //遍历所有子节点
            this.$refs.tabletree.toggleRowSelection(item, true); //切换该子节点选中状态

            item.isChecked = true;
          });
          row.isChecked = true; //当前行isChecked标志元素切换为false
        } else {
          row.children.map((item) => {
            this.$refs.tabletree.toggleRowSelection(item, false);
            item.isChecked = false;
          });
          row.isChecked = false;
        }
      }
    },
    selectAll(selection) {
      // selection 是选中的数据集合
      this.$refs.tabletree.data.map((items) => {
        //使用$ref获取注册的子组件信息，用data获取所有行，并用map函数遍历行
        if (items.children) {
          if (!items.isChecked) {
            //若遍历出来的行未选中
            this.$refs.tabletree.toggleRowSelection(items, true); //行变为选中状态
            items.isChecked = true; //更新标志参数
            items.children.map((item) => {
              //遍历子节点并改变状态与标志参数
              this.$refs.tabletree.toggleRowSelection(item, true);
              item.isChecked = true;
            });
          } else {
            //选中状态同理
            this.$refs.tabletree.toggleRowSelection(items, false);
            items.isChecked = false;
            items.children.map((item) => {
              this.$refs.tabletree.toggleRowSelection(item, false);
              item.isChecked = false;
            });
          }
        } else {
          if (!items.isChecked) items.isChecked = true;
          else items.isChecked = false;
        }
      });
      // console.log(this.orgs)
    },

    // 菜单权限-保存
    menuPermSave() {
      let data = [];
      this.permissions.selecttree.map((items) => {
        if (items.isChecked) {
          let ButtonLis = [];
          if (items.Btnlis.length > 0) {
            items.Btnlis.filter((x) => {
              return x.ischecked == true;
            }).forEach((x) => {
              ButtonLis.push(x.GuId);
            });
          }
          let model = {
            MenuGid: items.GuId,
            ButtonLis: ButtonLis.join(","),
          };
          data.push(model);
        }
      });

      console.info(data);
      this.loading = true;
      reqjson(
        "post",
        "/SysUserApi/ModifyPermissions?token=" +
          this.$jsutils.sessionget("token") +
          "&gid=" +
          this.permissions.usergid,
        data
      )
        .then((x) => {
          this.loading = false;
          if (x.success) {
            this.dataAccessshow = false;
            this.$message.success("操作成功!");
            this.getdata();
          } else {
            this.$message.error(x.data);
          }
        })
        .catch((x) => {
          this.loading = false;
          this.$message.error(x.data);
        });
    },
    //----数据权限end

    //获取菜单信息
    getmenu(ParentId) {
      let lis = this.permissions.list.filter((x) => {
        return x.ParentId == ParentId;
      });
      let newlis = [];
      lis.forEach((x, i) => {
        let userRoleAuthorizationmode =
          this.permissions.userRoleAuthorization.filter((p) => {
            return p.MenuGid == x.GuId;
          });
        let isChecked = false;
        if (userRoleAuthorizationmode.length > 0) {
          isChecked = true;
          if (x.buttons.length > 0) {
            x.buttons.forEach((item) => {
              //循环按钮列表
              if (userRoleAuthorizationmode[0].ButtonLis.includes(item.GuId))
                //存在授权列表中
                item.ischecked = true;
            });
          }
        }

        let m = {
          Id: x.Id,
          GuId: x.GuId,
          Icon: x.Icon,
          Name: x.Name,
          Type: x.Type,
          Address: x.Address,
          Sort: x.Sort,
          ParentId: x.ParentId,
          Btnlis: x.buttons,
          isChecked: isChecked,
          children: this.getmenu(x.Id),
        };
        newlis.push(m);
      });

      return newlis;
    },
    //选中绑定的值
    handleChange(value) {
      this.CompanyTreev = value;
    },
  },
};
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
</style>

 